package org.czx.datactruct.six;

import org.czx.datactruct.fifth.StackInterface;

import java.util.EmptyStackException;

/**
 * @author czx
 * @date 2020/9/10 16:50
 */
public class LinkedStack<T> implements StackInterface<T> {
    private Node topNode;

    public LinkedStack() {
        topNode = null;
    }
    @Override
    public void push(T newEntry) {
        topNode = new Node(newEntry, topNode);
    }

    @Override
    public T pop() {
        T top = peek();
        assert top != null;
        topNode = topNode.next;
        return top;
    }

    @Override
    public T peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        } else {
            return topNode.data;
        }
    }

    @Override
    public boolean isEmpty() {
        return topNode != null;
    }

    @Override
    public void clear() {
        topNode = null;
    }

    private class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
